<template>
   <div  class="BoxChart" style="margin-top:10px;">
        <div class="BoxChart_title">
            <a-card style="height:350px;" id="report-view">
                <div slot="title">
                    <div style="margin-bottom:5px">{{chartconfig[indexID].name}}
                        <Poptip trigger="hover"  placement="top-start">
                            <Icon type="ios-paper-outline" style="margin-left:5px"/>
                            <span slot="content" :style="isColor">{{chartconfig[indexID].remark==''?"暂无备注":chartconfig[indexID].remark}}</span>
                        </Poptip>
                    </div>
                    <div style="font-size:12px">
                        <span> {{date}}</span>
                        <span v-if="JSON.parse(chartconfig[indexID].time).type=='relative'" class="vertical">|</span>
                        <span v-if="JSON.parse(chartconfig[indexID].time).type=='relative'">{{dynamicTime}}</span>
                    </div>
                </div>
                <a href="#" slot="extra">
                    <Dropdown trigger="click">
                        <a href="javascript:void(0)">
                            <i type="md-close" class="del iconfont icon-gengduo"  size="20"></i>
                        </a>
                        <Dropdown-menu slot="list" style="width:100px">
                            <Dropdown-item  disabled>小</Dropdown-item>
                            <Dropdown-item :selected='chartconfig[indexID].size=="normal"'>中</Dropdown-item>
                            <Dropdown-item disabled>大</Dropdown-item>
                            <Dropdown-item  @click.native="set()" divided >设置</Dropdown-item>
                            <Dropdown-item  @click.native="delCharts(chartconfig[indexID].id)">删除</Dropdown-item>
                        </Dropdown-menu>
                    </Dropdown>
                </a>
                <div :id="`chart`+chartconfig[indexID].id" class="echarts"></div>
            </a-card>
        </div>
    </div>
</template>

<script type="text/ecmascript-6">
import setModule from '../components/setModule'
import bus from '../components/bus.js'
import FunnelQueryConfigUtil from '../utils/FunnelQueryConfigUtil'
import ElementResize from "../../components/ElementResize";
  export default {
    props:['chartconfig','indexID',"events","properties","measures","dashboardId","projectId"],
    components:{
        setModule
    },
    data(){
        return{
            date:"",
            config:null,
            chart: {
                funnelChart: null,
            },
            resultSet:[],
            dimension:null,
            dynamicTime:''
        }
    },
    mounted() {
        this.chart.funnelChart = this.$echarts.init(document.getElementById('chart'+this.chartconfig[this.indexID].id), 'light');
        this.chart.funnelChart.setOption(this.getChartOptions(), true);
        ElementResize.on(document.getElementById('report-view'), () => {
            this.chart.funnelChart.resize();
        })
        this.config=JSON.parse(this.chartconfig[this.indexID].config)
        this.getResultSet()
        let _that=this
        let times=JSON.parse(_that.chartconfig[_that.indexID].time)
            if(times.type == 'absolute'){
                times.values[0]=this.$sessionStore.getDay(-times.values[0])
                times.values[1]=this.$sessionStore.getDay(-times.values[1])
                this.date=times.values[0]+"~"+times.values[1]
            }else if(times.type == 'relative'){
                this.date=times.values[0]+"~"+times.values[1]
                let newdata1=this.dateDiff( times.values[0])
                let newdata2=this.dateDiff( times.values[1])
                if(this.$sessionStore.getDay(0)==times.values[1]&&this.$sessionStore.getDay(0)!==times.values[0]){
                    this.dynamicTime='最近'+newdata1+'天'
                }else if(this.$sessionStore.getDay(0)==times.values[1]&&this.$sessionStore.getDay(0)==times.values[0]){
                     this.dynamicTime='今日'
                }else {
                    this.dynamicTime='过去'+newdata2+'天~过去'+newdata1+'天'
                }
            }
        
    },
    computed:{
        isColor:function(){
          if(this.chartconfig[this.indexID].remark==''){
              return "color:#BFBFCD"
          }
      }
    },
    methods:{
        set(){
             this.$router.replace({path:'/main/funnel_analysis',query:{id:2,indexID:this.indexID}})
        },
        getResultSet(){
             this.$axios.post(this.$api.report + "/analysis/funnel" /*"https://www.easy-mock.com/mock/5d65d552a44ba847d32aff4a/reportservice/v1/analysis/funnel"*/,
                    {
                        time: {start: "2019-08-24", end: "2019-11-22", unit: "none"},
                        config: FunnelQueryConfigUtil.deleteKey(this.config)
                    },
                    {
                        headers: {
                            "Authorization": "Bearer "+this.$sessionStore.fetch(),
                            "Accept": "application/json"
                        },
                        params: {
                            projectId: this.$store.state.projectId
                        }
                    }).then(response => {
                    if (response.status === 200) {
                        this.resultSet = response.data.map(data => {
                            if(data[this.config.dimension] === '') {
                                data[this.config.dimension] = "未知";
                            }
                            return data;
                        });
                        this.updateChart()
                    }
                })
                    .catch(error => {
                        console.log(error);
                    }).finally(() => {
                    // this.loading = false;
                });
        },
        getUnit: function(measureName) {
                let unit = '';
                switch(measureName) {
                    case 'session_id':
                        unit = '会话';
                        break;
                    case 'eship_id':
                        unit = '人';
                        break;
                    default:
                        unit = '';
                        break;
                }
                return unit;
            },
         getChartOptions: function() {
                let options = {
                    tooltip: {
                        trigger: 'item',
                        // formatter: "{b} <br/>"+this.getUnit(this.config.funnel.measure.name)+"数 : {c}<br/>转化率 : {d}"
                        formatter: params => {
                            return params.data.name +"<br/>"+this.getUnit(this.config.funnel.measure.name)+"数 : "+params.data.value+ "<br/>转化率 : "+params.data.rate + "%";
                        }
                    },
                    toolbox: {
                        feature: {
                            dataView: {readOnly: false},
                            restore: {},
                            saveAsImage: {}
                        }
                    },
                    legend: {
                        data: []
                    },
                    calculable: true,
                    series: [
                    ]
                };
                return options;
            },
        updateChart: function() {
                let options = this.getChartOptions();
                for(let i = 0; i < this.config.funnel.steps.length; i++) {
                    options.legend.data.push(this.config.funnel.steps[i].name);
                }
                    for(let i = 0; i < this.resultSet.length; i++) {
                        if(this.resultSet.length > 0) {
                            let seriesData = [];
                            let seriesName = "总体";
                            let startStepValue = 1;
                            let endStepValue = 0;
                            let prevStep = null;
                            for(let j = 0; j < this.config.funnel.steps.length; j++) {
                                let step = this.config.funnel.steps[j];
                                if(step.order === 1){
                                    startStepValue = this.resultSet[0][step.event+"_"+step.order]
                                } else if(step.order === this.config.funnel.steps.length) {
                                    endStepValue = this.resultSet[0][step.event+"_"+step.order];
                                }
                                let rate = 0;
                                if(step.order === 1) {
                                    rate = 100;
                                }
                                else if(this.resultSet[0].hasOwnProperty(prevStep.event+"_"+prevStep.order)) {
                                    rate = Math.ceil(this.resultSet[0][step.event+"_"+step.order] * 100 / this.resultSet[0][prevStep.event+"_"+prevStep.order])
                                }
                                seriesData.push({
                                    name: step.name,
                                    value: this.resultSet[0][step.event+"_"+step.order],
                                    rate: rate
                                });
                                prevStep = step;
                            }
                            options.title = {
                                text: seriesName,
                                subtext: "总转换率："+ Math.ceil(endStepValue*100/startStepValue)+"%"
                            };
                            options.series.push({
                                name: seriesName,
                                type: 'funnel',
                                data: seriesData,
                                label: {
                                    show: true,
                                    position: 'inside',
                                    formatter: params => {
                                        return params.data.name +"\n"+params.data.value+this.getUnit(this.config.funnel.measure.name)+"("+params.data.rate + "%)";
                                    }
                                },
                                width: "80%",
                                left: "10%"
                            });
                        }
                }
                this.chart.funnelChart.setOption(options, true);
            },
        delCharts(del_id){
            let _that = this;
            this.$axios.delete(_that.$api.report +'/dashboard-pro/'+_that.dashboardId[0].id+'/block/'+del_id,
                {
                    headers: {
                        "Authorization": "Bearer "+this.$sessionStore.fetch(),
                        'Content-type': 'application/json'
                    },
                    params: {
                        projectId:this.$store.state.projectId
                    }
                }
            )
            .then(function(res){
                _that.$Message.info('删除成功');
                _that.chartconfig.map((item,index)=>{
                    if(item.id == del_id){
                        _that.chartconfig.splice(index,1);
                    }
                    return true; 
                })
            }).catch(function(err){
                console.log(err);
            })
        },
        dateDiff : function(sDate1) {
                var date2 = new Date();
                var date1 = new Date(Date.parse(sDate1.replace(/-/g,   "/")));
                var iDays = parseInt(Math.abs(date2.getTime()- date1.getTime()) /1000/60/60/24); 
                return iDays;
            },
    },
  }
</script>

<style  scoped>
.echarts{
    width: 100%;
    height: 310px;
}
.vertical{
    font-weight: 700;
    margin: 0 5px;
}
</style>
